'use strict';

let menusConfig = require('../../config/menus');
let Fiber = require('fibers');
let models = require('../models');
let UserDao = models.UserDao;
let StudentDao = models.StudentDao;
let util = require('util');

function generateMenus(user) {
    let menus = user.role.privileges.reduce((resultMenus, privilege) => {
        let curMenus = menusConfig[privilege.name];

        curMenus.forEach(curTab => {

            let dupTab = resultMenus.find(tab => {
                return tab.name == curTab.name;
            });

            if ( !dupTab ) {
                curTab.menus.forEach(menuItem => {
                    menuItem.url = util.format('/%s/%s/%s', privilege.name, curTab.name, menuItem.name);
                });
                if ( curTab.menus.length ) {
                    curTab.url = curTab.menus[0].url;
                }

                resultMenus.push(curTab);
            }
        });

        return resultMenus;
    }, []);

    return menus;
}

function main() {
    let user = UserDao.findOne({
        name: '0011'
    });

    let menus = generateMenus(user);
    console.log(JSON.stringify(menus, null, '  '));
}

module.exports = {
    generateMenus
};
